<template>
  <div class="app-container">
    <el-form :model="queryParam" ref="queryForm" :inline="true">
      <el-form-item label="题目ID：">
        <el-input v-model="queryParam.id" clearable style="width: 80px;"></el-input>
      </el-form-item>
      <el-form-item label="大学科：">
        <el-select v-model="queryParam.subjectParentId" placeholder="学科" @change="mainSubjectChange01" clearable style="width: 80px;">
          <el-option v-for="item in mainSubject" :key="item[0]" :value="item[0]" :label="item[1]"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="小学科：">
        <el-select v-model="queryParam.subjectId" placeholder="小学科" @change="mainSubjectChange02" clearable style="width: 200px;">
          <!-- 内层循环遍历对应主学科下的小学科列表，这里使用template标签包裹来进行正确的循环逻辑 -->
          <template v-for="mainItem in mainSubject01">
            <el-option v-for="subItem in mainItem[2]" :key="subItem[0]" :value="subItem[0]" :label="subItem[1]">
            </el-option>
          </template>
        </el-select>
      </el-form-item>
      <el-form-item label="题型：">
        <el-select v-model="queryParam.questionType" placeholder="题型" @change="mainSubjectChange" clearable style="width: 120px;">
          <el-option v-for="item in allQuestionType" :key="item[0]" :value="item[0]" :label="item[1]"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="题干：">
        <el-input v-model="queryParam.questionContent" clearable style="width: 120px"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">查询</el-button>
        <el-button type="primary"  @click="addQuestion()">添加</el-button>
        <el-form-item>
          <el-upload
            :action="actionUrl"
            :on-change="handleImageUpload"
            :show-file-list="false"
            :auto-upload="false"
          >
            <el-button size="small" type="primary" style="height: 35.5px; margin-left: 15px">上传文件</el-button>
          </el-upload>
        </el-form-item>
      </el-form-item>
    </el-form>
    <el-table v-loading="listLoading" :data="tableData"  border fit highlight-current-row style="width: 100%">
      <el-table-column prop="id" label="Id" width="80px"/>
      <el-table-column prop="subjectParentId" label="学科" width="100px">
        <template slot-scope="scope">
          {{ getSubjectName(scope.row.subjectParentId) }}
        </template>
      </el-table-column>
      <el-table-column prop="subjectName" label="科目"  width="200px"/>
      <el-table-column prop="questionTypeName"  label="题型"  width="100px"/>
      <el-table-column prop="articleContent" label="材料" show-overflow-tooltip/>
      <el-table-column prop="textContent" label="题干"  show-overflow-tooltip/>
      <el-table-column prop="score" label="分数" width="60px"/>
      <el-table-column prop="createTime" label="创建时间" width="160px"/>
      <el-table-column label="操作" align="center" width="220px">
        <template slot-scope="{row}">
          <el-button size="mini"   @click="showQuestion(row)">预览</el-button>
          <el-button size="mini"  @click="editQuestion(row)">编辑</el-button>
          <el-button size="mini"  type="danger" @click="deleteQuestion(row)" class="link-left">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="queryParam.pageIndex" :limit.sync="queryParam.pageSize"
                @pagination="search"/>
<!-- 使用 el-dialog 组件创建一个对话框，用于展示问题详情 -->
<el-dialog :visible.sync="questionShow.dialog" style="width: 100%;height: 100%">
  <!-- 使用 QuestionShow 组件展示问题详情，传入问题类型、问题数据和加载状态 -->
  <QuestionShow :qType="questionShow.qType" :question="questionShow.question" :qLoading="questionShow.loading"/>
</el-dialog>

  </div>
</template>

<script>
import { mapGetters, mapState } from 'vuex'
import Pagination from '@/components/Pagination'
import QuestionShow from './components/Show'
import questionApi from '@/api/question'

export default {
  components: { Pagination, QuestionShow },
  data () {
    return {
      queryParam: {
        id: null,
        questionType: null,
        subjectId: null,
        subjectParentId: null,
        questionContent: '',
        pageIndex: 1,
        pageSize: 10
      },
      subjectFilter: null,
      listLoading: true,
      tableData: [],
      total: 0,
      questionShow: {
        qType: 0,
        dialog: false,
        question: null,
        loading: false
      },
      allQuestionType: [],
      mainSubject: [],
      allQuestionType01: [],
      mainSubject01: [],
      actionUrl: '',
      sandFormFile: {
        file: '',
        fileType: 'question'
      }
    }
  },
  created () {
    this.search()
    this.typeChange()
  },
  methods: {
    extractSubjects () {
      const subjects = []
      this.mainSubject.forEach(([_, __, subSubjects]) => {
        subSubjects.forEach(([__, subjectName]) => {
          subjects.push(subjectName)
        })
      })
      return subjects
    },
    handleImageUpload (file) {
      if (file.size === 0) {
        this.$message.error('不能上传空文件')
        return false
      }
      // 检查文件类型是否为 JSON
      const allowedExtension = /\.json$/i
      if (!allowedExtension.test(file.name)) {
        this.$message.error('只能上传JSON文件')
        return false
      }
      // 检查文件名格式是否正确
      const yearRangePattern = `\\d{4}`
      const currentYear = new Date().getFullYear()
      const subjectNames = this.mainSubject.map(subjectGroup => subjectGroup[1])
      const subjectsPattern = subjectNames.join('|')
      const allowedPattern = new RegExp(`^(${subjectsPattern})_(${yearRangePattern})$`)
      console.log(allowedPattern)
      const fileNameWithoutExtension = file.name.split('.')[0].split('-')[0]
      const fileName = file.name.split('.')[0].split('-')[0].split('_')[0]
      const searchSubject = file.name.split('.')[0].split('-')[1]
      const num = fileNameWithoutExtension.split('_')[1]
      console.log(fileNameWithoutExtension)
      if (!allowedPattern.test(fileNameWithoutExtension) && num !== '') {
        this.$message.error('文件名格式不正确，应为学科_2000 - 科目')
        return false
      }
      const subjects = []
      this.mainSubject.forEach(([_, __, subSubjects]) => {
        subSubjects.forEach(([__, subjectName]) => {
          subjects.push(subjectName)
        })
      })
      if (!subjects.includes(searchSubject) && searchSubject !== '') {
        this.$message.error('当前科目不存在，请检查或先创建该科目')
        return false
      }
      const targetSubject = this.mainSubject.find(sub => sub[1] === fileName)
      if (targetSubject) {
        const subSubjects = targetSubject[2]
        const isMatch = subSubjects.some(subSub => subSub[1] === searchSubject)
        if (!isMatch && searchSubject !== '') {
          this.$message.error(`${searchSubject} 不属于 ${fileName}`)
          return false
        }
      } else {
        this.$message.error(`未找到名为 ${fileName} 的学科`)
        return false
      }
      if (num > currentYear) {
        this.$message.error('年份不能大于当前年份')
        return false
      }
      this.sandFormFile.file = file
      this.formLoading = true
      const formData = new FormData()
      let data = this.sandFormFile
      for (let key in data) {
        if (data[key] instanceof Array && data[key].length && data[key][0].raw) {
          for (let file of data[key]) {
            formData.append(key, file.raw)
          }
        } else if (data[key] && data[key].raw) {
          formData.append(key, data[key].raw)
        } else {
          formData.append(key, data[key])
        }
      }
      questionApi.uploadFileJson(formData).then(re => {
        console.log(this.pictures)
        this.$message.success(re)
        this.search()
        this.formLoading = false
      })
    },
    /**
     * 提交表单，重置页码为 1 并调用搜索方法
     */
    submitForm () {
      this.queryParam.pageIndex = 1
      console.log(this.queryParam)
      this.search()
      this.typeChange()
    },
    getSubjectName (subjectParentId) {
      for (let subject of this.mainSubject) {
        if (subject[0] === subjectParentId) {
          return subject[1]
        }
      }
      return ''
    },
    /**
     * 搜索方法，用于获取问题列表数据
     * 该方法会设置列表加载状态为 true，然后调用 questionApi 的 pageList 方法获取数据
     * 获取到数据后，会更新表格数据、总条数、当前页码，并设置列表加载状态为 false
     */
    search () {
      this.listLoading = true
      questionApi.pageList(this.queryParam).then(data => {
        const re = data.response
        this.tableData = re.list
        this.total = re.total
        this.queryParam.pageIndex = re.pageNum
        this.listLoading = false
      })
    },
    typeChange () {
      this.listLoading = true
      questionApi.selectType().then(data => {
        if (data.code === 1) {
          const re = data.response[0]
          this.mainSubject = re.mainSubject
          this.allQuestionType = re.allQuestionType
          this.allQuestionType01 = re.allQuestionType
          this.mainSubject01 = re.mainSubject
        } else {
          console.error('获取数据失败，原因：', data.message)
        }
        this.listLoading = false
      }
      )
    },
    mainSubjectChange () {
      // 这里编写当主科目选项改变时需要执行的逻辑，例如加载对应主科目的相关题型等
      console.log('题型选项发生改变，当前选中的值为：', this.queryParam.questionType)
    },
    mainSubjectChange02 () {
      // 这里编写当主科目选项改变时需要执行的逻辑，例如加载对应主科目的相关题型等
      console.log('小科目选项发生改变，当前选中的值为：', this.queryParam.subjectId)
    },
    mainSubjectChange01 () {
      // 这里编写当主科目选项改变时需要执行的逻辑，例如加载对应主科目的相关题型等
      console.log('主科目选项发生改变，当前选中的值为：', this.queryParam.subjectParentId)
      this.allQuestionType = this.allQuestionType01
      this.allQuestionType = this.allQuestionType.filter(data => data[2] === this.queryParam.subjectParentId)
      this.mainSubject01 = this.mainSubject.filter(data => data[0] === this.queryParam.subjectParentId)
    },

    addQuestion () {
      this.$router.push({ name: 'questionTypeInfo' })
    },
    /**
 * 显示问题详情
 * 该方法用于获取问题详情数据，并将其显示在对话框中
 * @param {Object} row - 表格中的一行数据，包含问题的ID
 */
    showQuestion (row) {
      let _this = this
      // 打开问题详情对话框
      this.questionShow.dialog = true
      // 设置问题详情加载状态为 true
      this.questionShow.loading = true
      // 调用 questionApi 的 select 方法获取问题详情数据
      questionApi.select(row.id).then(re => {
        // 将问题类型赋值给 questionShow 对象的 qType 属性
        _this.questionShow.qType = re.response.questionType
        // 将问题详情数据赋值给 questionShow 对象的 question 属性
        _this.questionShow.question = re.response
        // 设置问题详情加载状态为 false
        _this.questionShow.loading = false
      })
    },

    /**
 * 编辑问题
 * 该方法用于根据问题类型获取编辑问题的URL，并跳转到该URL
 * @param {Object} row - 表格中的一行数据，包含问题的ID和类型
 */
    editQuestion (row) {
      this.$router.push({ name: 'questionTypeInfo', query: { id: row.id } })
    },

    deleteQuestion (row) {
      let _this = this
      questionApi.deleteQuestion(row.id).then(re => {
        if (re.code === 1) {
          _this.search()
          _this.$message.success(re.message)
        } else {
          _this.$message.error(re.message)
        }
      })
    }
  },
  computed: {
    /**
     * 获取枚举格式化方法
     * 该方法用于获取 enumItem 模块中的 enumFormat 方法
     */
    ...mapGetters('enumItem', ['enumFormat']),

    /**
     * 获取问题类型枚举
     * 该方法用于获取 enumItem 模块中 exam 模块下 question 类型的枚举
     */
    ...mapState('enumItem', {
      questionType: state => state.exam.question.typeEnum,
      /**
       * 获取问题编辑URL枚举
       * 该方法用于获取 enumItem 模块中 exam 模块下 question 编辑URL的枚举
       */
      editUrlEnum: state => state.exam.question.editUrlEnum,
      /**
       * 获取用户级别枚举
       * 该方法用于获取 user 模块中 level 的枚举
       */
      levelEnum: state => state.user.levelEnum

    }),
    // aa
    /**
     * 获取学科枚举格式化方法
     * 该方法用于获取 exam 模块中的 subjectEnumFormat 方法
     */
    ...mapGetters('exam', ['subjectEnumFormat']),

    /**
     * 获取学科列表
     * 该方法用于获取 exam 模块中的 subjects 数组
     */
    ...mapState('exam', { subjects: state => state.subjects })
  }

}
</script>
